import React, {Component} from "react";
import {
  Dimensions,
  Image,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  DeviceEventEmitter,
  View
} from "react-native";
import {Modal} from "antd-mobile";
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";

import md5 from "md5";
import HTTP from "../../libs/HTTP";
import {loginUrl} from "../../libs/api";

import {getCurrentUser, getDeepUserInfo, setLoginUserPwd, setUserInfo, getLoginUserPwd, resetLoginUserPwd, isProducer} from "../../libs/Libs";

const { width, height } = Dimensions.get("window");

const background = require("./login1_bg.png");
const lockIcon = require("./signup_lock.png");
const personIcon = require("./signup_person.png");

const alert = Modal.alert

export default class Login extends Component {
  static navigationOptions: {
    statusBarStyle: 'light-content',
  }

  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      isLoading: false
    }
  }

  componentWillMount() {
  }

  componentDidMount() {
    console.log(this.props.navigation.state.params)
    const params = this.props.navigation.state.params || {}
    const isAutoLogin = params['autoLogin']
    console.log(isAutoLogin)
    getLoginUserPwd((username, password) =>  {
      this.setState({
        username: username,
        password: password || ""
      }, () => {
        if(isAutoLogin == false) {
          resetLoginUserPwd(username)
        } else {
          if(password !== undefined && password !== "") {
            this.login()
          }
        }

      })
    })
    // getDeepUserInfo((v = {}) => {
    //   if(v['userName'] !== undefined && v['userPassword'] !== undefined) {
    //     this.setState({
    //       username: v['userName'],
    //       password: ""
    //     })
    //     console.log('isAutoLogin: ', isAutoLogin)
    //     if(isAutoLogin == false) {
    //
    //     } else {
    //       this.loginWithRegistrationId(v['userName'], v['userPassword'])
    //     }
    //   }
    // })
    // ToastExample.show('Awesome', ToastExample.SHORT)
  }
  userNameChange = (text) => {
    this.setState({
      username: text
    })
  }
  passwordChange = (text) => {
    this.setState({
      password: text
    })
  }
  login = ()  => {
    const username = this.state.username
    const password = md5(this.state.password)
    console.log('username', username, ' password', password)
    this.loginWithRegistrationId(username, password, this.state.password)
  }
  loginWithRegistrationId(username, password, rawPassword) {
    this.setState({
      isLoading: true
    })
    const resp = HTTP.post(loginUrl(), {
      userName: username,
      userPassword: password
    },() => {
      this.setState({
        isLoading: false
      })
    }, (data) => {
      setUserInfo(data)
      setLoginUserPwd(username, rawPassword)
      if(isProducer()) {
        this.props.navigation.navigate('ProducerMenu')
      } else {
        this.props.navigation.navigate('Menu')
      }
    }, (data) => {
      alert('提示', data['message'])
    })
  }
  invokeRegister = () => {
    this.props.navigation.navigate('SignStack')
  }
  render() {
    return (
      <KeyboardAwareScrollView
        style={{ backgroundColor: '#4c69a5' }}
        resetScrollToCoords={{ x: 0, y: 0 }}
        scrollEnabled={false}
      >
        <StatusBar
          backgroundColor='#2f1f10'
          barStyle="light-content"
        />
        <ScrollView style={styles.container}>
          <Image source={background} style={styles.background} resizeMode="cover">
            <View style={styles.markWrap}>
              <Text style={{fontSize: 24}}>WINDER管理系统</Text>
            </View>
            <View style={styles.wrapper}>
              <View style={styles.inputWrap}>
                <View style={styles.iconWrap}>
                  <Image source={personIcon} style={styles.icon} resizeMode="contain" />
                </View>
                <TextInput
                  onChangeText={this.userNameChange}
                  value={this.state.username}
                  underlineColorAndroid="transparent"
                  placeholder="帐号"
                  placeholderTextColor="#999999"
                  style={styles.input}
                />
              </View>
              <View style={styles.inputWrap}>
                <View style={styles.iconWrap}>
                  <Image source={lockIcon} style={styles.icon} resizeMode="contain" />
                </View>
                <TextInput
                  onChangeText={this.passwordChange}
                  value={this.state.password}
                  underlineColorAndroid="transparent"
                  placeholderTextColor="#999999"
                  placeholder="密码"
                  style={styles.input}
                  secureTextEntry
                />
              </View>
              <TouchableOpacity activeOpacity={.5} style={{display: 'none'}}>
                <View>
                  <Text style={styles.forgotPasswordText}>忘记密码?</Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity activeOpacity={.5} onPress={this.login}>
                <View style={styles.button}>
                  <Text style={styles.buttonText}>登录</Text>
                </View>
              </TouchableOpacity>
            </View>

            <View style={styles.container}>
              <View style={styles.signupWrap}>
                <Text style={styles.accountText}>没有帐号?</Text>
                <TouchableOpacity activeOpacity={.5} onPress={this.invokeRegister}>
                  <View>
                    <Text style={styles.signupLinkText}>注册</Text>
                  </View>
                </TouchableOpacity>
              </View>
            </View>
          </Image>
        </ScrollView>
      </KeyboardAwareScrollView>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  markWrap: {
    height: 230,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'flex-end',
    paddingVertical: 30,
  },
  mark: {
    width: null,
    height: null,
    flex: 1,
  },
  mintitle: {
    fontSize: 32,
    fontWeight: 'bold',
    color: "#FF3366"
  },
  miniSubTitle: {
    fontSize: 16,
    color: "#FF3366"
  },
  background: {
    width,
    height,
  },
  backgroundTitle: {
    width: 200,
    height: 60
  },
  wrapper: {
    padding: 30
  },
  inputWrap: {
    flexDirection: "row",
    marginVertical: 10,
    height: 40,
    borderBottomWidth: 1,
    borderBottomColor: "#CCC"
  },
  iconWrap: {
    paddingHorizontal: 7,
    alignItems: "center",
    justifyContent: "center",
  },
  icon: {
    height: 20,
    width: 20,
  },
  input: {
    flex: 1,
    paddingHorizontal: 10,
    padding: 0,
    color: '#333333'
  },
  button: {
    backgroundColor: "#39C0E7",
    paddingVertical: 10,
    alignItems: "center",
    justifyContent: "center",
    marginTop: 30,
  },
  buttonText: {
    color: "#FFF",
    fontSize: 18
  },
  forgotPasswordText: {
    color: "#D8D8D8",
    backgroundColor: "transparent",
    textAlign: "right",
    paddingRight: 15,
  },
  signupWrap: {
    backgroundColor: "transparent",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center"
  },
  accountText: {
    color: "#D8D8D8"
  },
  signupLinkText: {
    color: "#666666",
    marginLeft: 5,
  }
});
